<template>
  <text class="ai-time">{{formattedDate}}</text>
</template>

<script>
  const LOCAL_TIME = {
    weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
    formats: {
      LT: 'HH:mm', // 00:32
      lll: 'YYYY年M月D日 HH:mm', // 2019年2月22日 00:28
      WT: 'dddd HH:mm', // 星期一 00:32
      YT: '昨天 HH:mm', // 昨天 00:32
    },
  }

  const REGEX_FORMAT = /YYYY|M|D|dddd|HH|mm/g;
  const MS_A_DAY = 24 * 60 * 60 * 1000;
  const MS_A_WEEK = MS_A_DAY * 7;

  const parseDate = (date) => {
    if (date instanceof Date) {
      return date
    }
    return new Date(date)
  }
  const getWeeHours = () => new Date(new Date().setHours(0, 0, 0, 0));
  const padStart = (n) => (n <= 9 ? '0' : '') + n;

  const getFormat = (date) => {
    const diff = getWeeHours().getTime() - date.getTime();

    if (diff < 0) {
      return 'LT'; // 今天
    }
    if (diff < MS_A_DAY) {
      return 'YT'; // 昨天
    }
    if (diff < MS_A_WEEK) {
      return 'WT'; // 这周
    }
    return 'lll';
  }

  export default {
    name: "ai-time",
    props: {
      date: [Number, String, Date]
    },
    data() {
      return {
        formattedDate: ""
      };
    },
    mounted() {
      this.formattedDate = this.formatDate(this.date)
    },
    methods: {
      formatDate(date) {
        const $d = parseDate(date);
        const format = LOCAL_TIME.formats[getFormat($d)];

        const dates = {
          YYYY: `${$d.getFullYear()}`,
          M: `${$d.getMonth() + 1}`,
          D: `${$d.getDate()}`,
          dddd: LOCAL_TIME.weekdays[$d.getDay()],
          HH: padStart($d.getHours()),
          mm: padStart($d.getMinutes()),
        };

        return format.replace(REGEX_FORMAT, (match) => dates[match]);
      }
    }
  }
</script>

<style lang="scss">
  .ai-time {
    font-size: 12px;
    color: var(--gray-3);
  }
</style>